package top.lingchen.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import top.lingchen.spring5.entity.Book;

import java.util.Arrays;
import java.util.List;

/**
 * @Author 凌宸
 * @create 2021-11-30 下午 6:01
 * @Description
 * @Version 1.0
 */
@Repository
public class BookDaoImpl implements BookDao{
    // 注入 JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 添加的方法
    @Override
    public void add(Book book) {
        // 1. 创建 sql 语句
        String sql = "insert into t_book values(?, ?, ?)";
        Object[] args = {book.getBookId(),book.getBookName(),book.getBookStatus()};
        // 2.调用方法实现
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

    @Override
    public void update(Book book) {
        String sql = "update t_book set book_name = ?, book_status = ? where book_id = ?";
        Object[] args = {book.getBookName(),book.getBookStatus(),book.getBookId()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

    @Override
    public void delete(String id) {
        String sql = "delete from t_book where book_id = ?";
        int update = jdbcTemplate.update(sql,id);
        System.out.println(update);
    }

    @Override
    public int count() {
        String sql = "select count(*) from t_book";
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public Book findById(String id) {
        String sql = "select * from t_book where book_id = ?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
        return book;
    }

    @Override
    public List<Book> findAllBooks() {
        String sql = "select * from t_book";
        List<Book> books = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
        return books;
    }

    @Override
    public void batchAddBooks(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?, ?, ?)" ;
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchUpdateBooks(List<Object[]> batchArgs) {
        String sql = "update t_book set book_name = ? , book_status = ? where book_id = ?" ;
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchDeleteBooks(List<Object[]> batchArgs) {
        String sql = "delete from t_book where book_id = ?" ;
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

}
